package sorting;

import edu.princeton.cs.algs4.StdIn;

/**
 * 归并排序算法类
 */
public class Merge {

    private static Comparable[] aux;//归并所需的辅助数组

    public static void sort(Comparable[] a) {
        aux = new Comparable[a.length];//一次性分配空间
        sort(a, 0, a.length - 1);
    }

    private static void sort(Comparable[] a, int l, int h) {
        if (h <= l) return;
        int m = l + (h - l) / 2;
        sort(a, l, m);
        sort(a, m + 1, h);
        merge(a, l, m, h);

    }

    private static void merge(Comparable[] a, int l, int m, int h) {
        //将a[l..m]和a[m+1..h]归并
        int i = l;
        int j = m + 1;
        for (int k = l; k <= h; k++) {
            aux[k] = a[k];
        }
        for (int k = l; k <= h; k++) {
            if (i > m) a[k] = aux[j++];
            else if (j > h) a[k] = aux[i++];
            else if (less(aux[i], aux[j])) a[k] = aux[i++];
            else a[k] = aux[j++];
        }


    }

    //less 对元素进行比较,是否v比w小
    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }

    //exch 将元素交换位置
    private static void exch(Comparable[] a, int i, int j) {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    //在单行中打印数组
    private static void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    //测试数组元素是否有序 从小到大
    public static boolean isSorted(Comparable[] a) {
        for (int i = 1; i < a.length; i++) {
            if (less(a[i], a[i - 1])) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String[] a = StdIn.readAllStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    }


}
